package pers.xiaojun.boot.module.system.service.auth;

import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import pers.xiaojun.boot.common.exception.BusinessException;
import pers.xiaojun.boot.module.system.constants.OAuth2ClientConstants;
import pers.xiaojun.boot.module.system.controller.auth.vo.AuthLoginReqVO;
import pers.xiaojun.boot.module.system.controller.auth.vo.AuthLoginRespVO;
import pers.xiaojun.boot.module.system.convert.AuthConvert;
import pers.xiaojun.boot.module.system.dao.entity.user.AdminUserDO;
import pers.xiaojun.boot.module.system.dao.redis.TokenRedisDAO;
import pers.xiaojun.boot.module.system.service.capthca.CaptchaService;
import pers.xiaojun.boot.module.system.service.oauth2.OAuth2TokenService;
import pers.xiaojun.boot.module.system.service.oauth2.dto.OAuth2TokenDTO;
import pers.xiaojun.boot.module.system.service.user.UserService;

import static pers.xiaojun.boot.module.system.constants.BusinessCodeConstants.AUTH_LOGIN_BED_CREDENTIALS;

/**
 * 认证服务层
 *
 * @author xiaojun
 * @since 2025-10-04
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserService userService;
    private final CaptchaService captchaService;
    private final PasswordEncoder passwordEncoder;
    private final OAuth2TokenService oAuth2TokenService;


    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // 校验验证码
        captchaService.verify(reqVO.getCaptchaKey(), reqVO.getCaptchaValue());

        // 获取用户信息
        AdminUserDO user = userService.getUserByUsername(reqVO.getUsername());
        if (user == null || !passwordEncoder.matches(reqVO.getPassword(), user.getPassword())) {
            throw new BusinessException(AUTH_LOGIN_BED_CREDENTIALS);
        }
        // 构建Token
        OAuth2TokenDTO token = oAuth2TokenService.createAccessToken(user.getId(), OAuth2ClientConstants.DEFAULT_CLIENT, null, null);
        // 成功后删除Redis中的值
        captchaService.removeCaptcha(reqVO.getCaptchaKey());

        return AuthConvert.INSTANCE.toAuthLoginRespVO(token);
    }

    @Override
    public void logout(String token) {
        oAuth2TokenService.removeAccessToken(token);

    }

    @Override
    public AuthLoginRespVO refreshAccessToken(String refreshToken) {
        OAuth2TokenDTO oAuth2Token = oAuth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.DEFAULT_CLIENT);
        return AuthConvert.INSTANCE.toAuthLoginRespVO(oAuth2Token);
    }


}
